package com.koron.standard.gradeStock.excel;

import cn.hutool.core.map.BiMap;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.AutoConverter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.koron.common.core.business.datadict.utils.DataDictTool;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author jzp
 * @since 2022/5/16
 */
public class GradeStringStringConvertor extends AutoConverter {

    /**
     * {
     *     字段名：{
     *         数据库值：前端显示值
     *     }
     * }
     */
    private final Map<String, BiMap<String, String>> fieldMap = new HashMap<>();
    private final String title = "$title$";

    /**
     * 初始化字典数据
     */
    public GradeStringStringConvertor(){
        // 验收级别 level
        BiMap<String, String> levelMap = new BiMap<>(DataDictTool.getDataDictByCode("standardManagement", "standard_check_level"));
        levelMap.put(title, "验收级别");

        // 专业 major
        BiMap<String, String> majorMap = new BiMap<>(DataDictTool.getDataDictByCode("publicDictionary", "common_major"));
        majorMap.put(title, "专业");

        // 字段和数据字典对应
        fieldMap.put("major", majorMap);
        fieldMap.put("level", levelMap);
    }

    @Override
    public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) {
        String key = fieldMap.get(contentProperty.getField().getName()).getKey(cellData.getStringValue());
        if (StrUtil.isNotEmpty(cellData.getStringValue()) && StrUtil.isEmpty(key)) {
            throw new IllegalArgumentException("找不到" + cellData.getStringValue() + "对应的" + fieldMap.get(contentProperty.getField().getName()).get(title));
        }
        return key;
    }

    @Override
    public WriteCellData<String> convertToExcelData(Object value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(fieldMap.get(contentProperty.getField().getName()).get(Objects.toString(value, "")));
    }

}
